<?php


namespace app\api\controller;


use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Db;
use think\Log;
use think\Model;

class Paycall extends Api
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    // 充值订单
    public function payUser()
    {
        $config = config('wechat_pay');
        $app = Factory::payment($config);


        $response = $app->handlePaidNotify(function ($message, $fail) {
            Log::write('验签成功');
            Log::write($message);
            //微信支付交易号
            $transaction_id = $message['transaction_id'];
            $order_number = $message['out_trade_no'];
            //现金收款
            $official_receipts = $message['cash_fee'];
            //订单金额
            $total_fee = $message['total_fee'] / 100;
            //支付时间
            $pay_time = strtotime($message['time_end']);

//            $order = Db::name('cashout')->field('id,user_id,orderno')->where(['orderno'=>$order_number])->find();
            $order = Db::name('cashout')->field('id,user_id,orderno,money')->where(['orderno' => $order_number])->find();
            if (!$order) {
                return true;
            }
            if ($message['return_code'] == 'SUCCESS') {
//                Log::write("订单信息成功数据");
//                Log::write($message);
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    //支付成功
                    $order_data = [
//                        'order_time'=>$pay_time,
                        'transaction_id' => $transaction_id,
//                        'actual_price'=>$official_receipts,
                        'money' => $total_fee,
                        'status' => 2,
                        'pay_time' => time(),// 支付时间
                    ];
                    // 更新数据
                    $upda = Db::name('cashout')->where('orderno', $order_number)->update($order_data);
                    Db::name('user')->where('id', $order['user_id'])->setInc('money', $order['money']);
                    // 给上级返利
//                    model('user')::item($order['user_id'],$order_number);
//                    model('user')::log($order['user_id'],$order_number);
                    if (!$upda) return $fail("修改订单状态失败,请稍后通知！");
//                    Log::write('订单:'.$order_number.'支付'.$total_fee.'元成功');
                    return true;
                } elseif ($message['return_code'] == 'FAIL') {
                    // 用户支付失败
                    return $fail('通信失败，请稍后再通知我');
                }
            } else {
                return $fail("通信失败，请稍后通知！");
            }
        });
        return $response;
    }


    // 生成订单
    public function payOrder()
    {
        $config = config('wechat_pay');
        $app = Factory::payment($config);

        $response = $app->handlePaidNotify(function ($message, $fail) {
            Log::write('验签成功');
            Log::write($message);
            //微信支付交易号
            $transaction_id = $message['transaction_id'];
            $order_number = $message['out_trade_no'];
            //现金收款
            $official_receipts = $message['cash_fee'];
            //订单金额
            $total_fee = $message['total_fee'] / 100;
            //支付时间
            $pay_time = strtotime($message['time_end']);

            $order = Db::name('order')->field('id,user_id,order_id,goods_id,cou_id,title,num')->where(['order_id' => $order_number])->find();
            if (!$order) {
                return true;
            }

            if ($message['return_code'] == 'SUCCESS') {
//                Log::write("订单信息成功数据");
//                Log::write($message);
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    //支付成功
                    $order_data = [
//                        'order_time'=>$pay_time,
                        'transaction_id' => $transaction_id,
//                        'actual_price'=>$official_receipts,
                        'money' => $total_fee,
                        'status' => 2,
                        'pay_time' => time(),// 支付时间
                    ];

                    // 更新数据
                    $upda = Db::name('order')->where('order_id', $order_number)->update($order_data);
                    // 更改规格的库存
                    $item = Db::name('goods')->where('id', $order['goods_id'])->value('item');

                    $item = json_decode($item, true);

                    foreach ($item as &$val) {
                        if ($val['title'] == $order['title']) {
                            $val['stock'] = $val['stock'] - $order['num'];
                        }
                    }
                    // 删除优惠券id
                    if ($order['cou_id']) {
                        Db::name('user_coupons')->where('id', $order['cou_id'])->setDec('num', 1);
                        Db::name('user_coupons')->where('id', $order['cou_id'])->update(['status' => 2]);
                    }
                    $item = json_encode($item);
                    Db::name('goods')->where('id', $order['goods_id'])->update(['item' => $item]);
                    // 给上级返利
//                    model('user')::item($order['user_id'],$order_number);
                    model('user')::log($order['user_id'], $order_number);
                    model('user')::userVip($order['user_id'], $order_number);
                    if (!$upda) return $fail("修改订单状态失败,请稍后通知！");
//                    Log::write('订单:'.$order_number.'支付'.$total_fee.'元成功');
                    return true;
                } elseif ($message['return_code'] == 'FAIL') {
                    // 用户支付失败
                    return $fail('通信失败，请稍后再通知我');
                }
            } else {
                return $fail("通信失败，请稍后通知！");
            }
        });
        return $response;
    }



    public function openUser()
    {
        $config = config('wechat_pay');
        $app    = Factory::payment($config);

        $response = $app->handlePaidNotify(function ($message, $fail) {
            file_put_contents("sites.txt",$message);
            Log::write('验签成功');
            Log::write($message);
            file_put_contents("sites.txt",$message);
            //微信支付交易号
            $transaction_id =  $message['transaction_id'];
            $order_number = $message['out_trade_no'];
            //现金收款
            $official_receipts = $message['cash_fee'];
            //订单金额
            $total_fee = $message['total_fee']/100;
            //支付时间
            $pay_time = strtotime($message['time_end']);

            $order = Db::name('user_vip')->field('id,user_id,order_id,vip_id')->where(['order_id'=>$order_number])->find();
            if (!$order) {
                return true;
            }
            $uv    = Db::name('user_vip')->where(['user_id'=>$order['user_id'],'is_delete'=>1,'status'=>2])->find();

            // 获取开通会员的信息
            $vip = Db::name('vip')->where('id',$order['vip_id'])->find();
            // 生成数据
            $end_time = time() + $vip['day'] * 86400;
            if ($message['return_code'] == 'SUCCESS') {
                Log::write("订单信息成功数据");
                Log::write($message);
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    //支付成功
                    $order_data = [
//                        'order_time'=>$pay_time,
                        'transaction_id' => $transaction_id,
//                        'actual_price'=>$official_receipts,
                        'money'     => $total_fee,
                        'status'    => 2,
                        'pay_time'  => time(),// 支付时间
                    ];
                    if($uv)
                    {
                        $order_data['start_time'] = time();
                        $order_data['end_time']   = $uv['end_time'] + ($vip['day'] * 86400);
                        Db::table('fa_user_vip')->where(['order_id'=>$uv['order_id']])->update(['is_delete'=>2]);
                    }else{
                        $order_data['start_time'] = time();
                        $order_data['end_time']   = $end_time;
                    }
                    // 更新数据
                    $upda = Db::name('user_vip')->where('order_id',$order_number)->update($order_data);
                    Db::name('user')->where('id',$order['user_id'])->update(['is_vip'=>1]);
                    if (!$upda) return $fail("修改订单状态失败,请稍后通知！");
//                    Log::write('订单:'.$order_number.'支付'.$total_fee.'元成功');
                    return true;
                } elseif ($message['return_code'] == 'FAIL') {
                    // 用户支付失败
                    return $fail('通信失败，请稍后再通知我');
                }
            }else{
                return $fail("通信失败，请稍后通知！");
            }
        });
        return $response;

    }

    /*
     * 开通会员
     * */
    public function openVipCard()
    {
        $config = config('wechat_pay');
        $app = Factory::payment($config);

        $response = $app->handlePaidNotify(function ($message, $fail) {
            Log::write('验签成功');
            Log::write($message);
            //微信支付交易号
            $transaction_id = $message['transaction_id'];
            $order_number = $message['out_trade_no'];
            //现金收款
            $official_receipts = $message['cash_fee'];
            //订单金额
            $total_fee = $message['total_fee'] / 100;
            //支付时间
            $pay_time = strtotime($message['time_end']);

            $order = Db::name('vip_card_order')->field('id,user_id,order_id,vip_id')->where(['order_id' => $order_number])->find();
            if (!$order) {
                return true;
            }

            // 获取开通会员的信息
            $vip = Db::name('vip_card')->where('id', $order['vip_id'])->find();
            // 生成数据
            $end_time = time() + $vip['day'] * 86400;
            if ($message['return_code'] == 'SUCCESS') {
                Log::write("订单信息成功数据");
                Log::write($message);
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    try {
                        Db::startTrans();
                        //支付成功
                        $order_data = [
                            'transaction_id' => $transaction_id,
                            'money' => $total_fee,
                            'status' => 2,
                            'pay_time' => time(),// 支付时间
                        ];

                        $order_data['start_time'] = time();
                        $order_data['end_time'] = $end_time;
                        // 更新数据
                        Db::name('vip_card_order')->where('order_id', $order_number)->update($order_data);

                        //查询会员卡信息
                        $vip_card = Db::name('vip_card')->where(['id' => $order['vip_id']])->find();

                        //下发会员卡
                        $this->createVipCard($order['user_id'], $end_time, $vip_card['pay_goods_nums']);
                        //上级返利
                       model('user')::item($order['user_id'],$order_number);

                        Db::commit();
                    } catch (\Exception $e) {
                        Db::rollback();
                        return $fail("修改订单状态失败,请稍后通知！");
                    }
                    return true;
                } elseif ($message['return_code'] == 'FAIL') {
                    // 用户支付失败
                    return $fail('通信失败，请稍后再通知我');
                }
            } else {
                return $fail("通信失败，请稍后通知！");
            }
        });
        return $response;

    }


    public function payVipGoodsOrder()
    {
        $config = config('wechat_pay');
        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            Log::write('验签成功');
            Log::write($message);
            //微信支付交易号
            $transaction_id = $message['transaction_id'];
            $order_number = $message['out_trade_no'];
            //订单金额
            $total_fee = $message['total_fee'] / 100;
            //支付时间
            $pay_time = strtotime($message['time_end']);

            $order = Db::name('order')->field('id,user_id,order_id,goods_id,title,num')->where(['order_id' => $order_number])->find();
            if (!$order) {
                return true;
            }

            if ($message['return_code'] == 'SUCCESS') {
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    //支付成功
                    $order_data = [
                        'transaction_id' => $transaction_id,
                        'money' => $total_fee,
                        'status' => 2,
                        'pay_time' => time(),// 支付时间
                    ];
                    // 更新数据
                    $upda = Db::name('order')->where('order_id', $order_number)->update($order_data);
                    // 更改规格的库存
                    $item = Db::name('goods')->where('id', $order['goods_id'])->value('item');

                    $item = json_decode($item, true);

                    foreach ($item as &$val) {
                        if ($val['title'] == $order['title']) {
                            $val['stock'] = $val['stock'] - $order['num'];
                        }
                    }
                    $item = json_encode($item);
                    Db::name('goods')->where('id', $order['goods_id'])->update(['item' => $item]);
                    model('user')::log($order['user_id'], $order_number);
                    //减少vip购物次数
                    Db::name('user_card')->where(['member_id' => $order['user_id'], 'status' => 1])->setDec('nums', $order['num']);
                    if (!$upda) return $fail("修改订单状态失败,请稍后通知！");
                    return true;
                } elseif ($message['return_code'] == 'FAIL') {
                    // 用户支付失败
                    return $fail('通信失败，请稍后再通知我');
                }
            } else {
                return $fail("通信失败，请稍后通知！");
            }
        });
        return $response;
    }


    public function addMaterialUrl()
    {
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=" . $access_token;
        $Img = './logo.jpg'; // 一定要图片服务器的绝对路径,文件名同目录下 其他目录自己指定
        $file = new \CURLFile(realpath($Img));
        $data['buffer'] = $file;           // 文件的数据流
        $res = $this->request_post($url, $data);
        return json_decode($res, true)['url'];
    }


    public function request_Get($url)
    {
        $curl = curl_init();
        $timeout = 5;
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, $timeout);
        $tmpInfo = curl_exec($curl);     //返回api的json对象
        //关闭URL请求
        curl_close($curl);
        return $tmpInfo;    //返回json对象
    }


    public function createVipCard($user_id, $endTime, $nums)
    {
        $access_token = $this->getAccessToken();
        $url = "https://api.weixin.qq.com/card/create?access_token=" . $access_token;
        $data = array(
            "card" => array(
                "card_type" => "MEMBER_CARD",
                "member_card" => array(
                    "background_pic_url" => "http://mmbiz.qpic.cn/sz_mmbiz_jpg/SCwzu8EAEpn8diblfNiaumDSde0gWeUGQ2Ovb78ACXU3rXOmd7tsLodCiavC5ISXH1RghBqOZODHlmOxluibe2bIMQ/0?from=appmsg",
                    "base_info" => array(
                        "logo_url" => "http://mmbiz.qpic.cn/sz_mmbiz_jpg/SCwzu8EAEpn8diblfNiaumDSde0gWeUGQ2Ovb78ACXU3rXOmd7tsLodCiavC5ISXH1RghBqOZODHlmOxluibe2bIMQ/0?from=appmsg",
                        "brand_name" => "左邻超市",
                        "code_type" => "CODE_TYPE_BARCODE",
                        "title" => "会员卡",
                        "color" => "Color060",
                        "notice" => "使用时请告诉客服会员卡号",
                        "description" => "不可与其他优惠同享",
                        "date_info" => array(
                            "type" => "DATE_TYPE_FIX_TIME_RANGE",
                            "begin_timestamp" => time(),
                            'end_timestamp' => $endTime
                        ),
                        "sku" => array(
                            "quantity" => 1
                        ),
                        "get_limit" => 1,
                        "use_custom_code" => false,
                        "can_give_friend" => false,
                        "custom_url_name" => '进入商城',
                        "custom_app_brand_user_name" => "gh_12156627fda3@app",
                        "custom_app_brand_pass" => "/pages/index/index"

                    ),
                    "custom_field1" => array(
                        "name_type" => 'FIELD_NAME_TYPE_TIMS',
                        "name" => "次数",
                        'url' => 'https://baidu.com',
                        "app_brand_user_name" => "gh_12156627fda3@app",
                        "app_brand_pass" => "/pages/my-vip/my-vip"
                    ),

                    "custom_cell1" => array(
                        "tips" => '测试测试'
                    ),

                    "advanced_info" => array(
                        "abstract" => array(
                            "abstract" => "1.特权服务\n2.专员服务\n3.每日10次特权",
                            "icon_url_list" => array(
                                "http://mmbiz.qpic.cn/sz_mmbiz_jpg/SCwzu8EAEpn8diblfNiaumDSde0gWeUGQ2Ovb78ACXU3rXOmd7tsLodCiavC5ISXH1RghBqOZODHlmOxluibe2bIMQ/0?from=appmsg"
                            )
                        ),
                        "text_image_list" => array(
                            array(
                                "image_url" => "http://mmbiz.qpic.cn/sz_mmbiz_jpg/SCwzu8EAEpn5pEBfzMdHoian3rM7RAsA3F57avyCFBH22svpOCx1bicZr5XyTFLcibl9VtrhkBsxd2VI3Ws0chYiaA/0?from=appmsg",
                                "text" => "开启你的购物之旅！"
                            )
                        )
                    ),
                    "supply_bonus" => false,
                    "supply_balance" => false,
                    "prerogative" => "每天用卡可抵消一次特权",
                    "auto_activate" => true,
                    "activate_app_brand_user_name" => "gh_12156627fda3@app",
                    "activate_app_brand_pass" => "/pages/my/my",
                    "activate_url" => "http://www.qq.com"
                )
            )
        );


// 将数组转换为JSON字符串
        $json_data = json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        $res = $this->request_post($url, $json_data);
        if ($res['errmsg'] == 'ok') {
            //执行添加
            $min = 1000000000; // 最小的10位数
            $max = 9999999999; // 最大的10位数
            $order_id = mt_rand($min, $max);
            Db::name('user_card')->insert([
                'number_id' => $order_id,
                'member_id' => $user_id,
                'card_id' => $res['card_id'],
                'status' => 0,
                'vip_card_time' => $endTime,
                'nums' => $nums,
                'create_time' => time(),
                'update_time' => time(),
            ]);
        }

        return true;
    }


    public function utf8ize($mixed)
    {
        if (is_array($mixed)) {
            foreach ($mixed as $key => $value) {
                $mixed[$key] = $this->utf8ize($value);
            }
        } elseif (is_string($mixed)) {
            return utf8_encode($mixed);
        }
        return $mixed;
    }


    /**
     * 发送post请求
     * @param string $url
     * @param string $param
     * @return bool|mixed
     */
    function request_post($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch); //运行curl
        curl_close($ch);
        return json_decode($data, TRUE);
    }


    public function getAccessToken()
    {
        $config = config('wx_program');
        $appid = $config['app_id'];
        $appsecret = $config['secret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
        $access = json_decode($this->request_Get($url), true);
        $access_token = $access['access_token'];
        // print_r($access);

        return $access_token;
    }


    /*
     * 购物车下单
     * */
    public function payGoods()
    {
        $config = config('wechat_pay');
        $app = Factory::payment($config);

        $response = $app->handlePaidNotify(function ($message, $fail) {
            Log::write('验签成功');
            Log::write($message);
            //微信支付交易号
            $transaction_id = $message['transaction_id'];
            $order_number = $message['out_trade_no'];
            //现金收款
            $official_receipts = $message['cash_fee'];
            //订单金额
            $total_fee = $message['total_fee'] / 100;
            //支付时间
            $pay_time = strtotime($message['time_end']);

            $order = Db::name('order')->field('id,user_id,order_id,pid,goods_id,name,title,cou_id')->where(['order_id' => $order_number])->find();

            if (!$order) {
                return true;
            }
            if ($message['return_code'] == 'SUCCESS') {
//                Log::write("订单信息成功数据");
//                Log::write($message);
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    //支付成功
                    $order_data = [
//                        'order_time'=>$pay_time,
                        'transaction_id' => $transaction_id,
//                        'actual_price'=>$official_receipts,
                        'money' => $total_fee,
                        'status' => 2,
                        'pay_time' => time(),// 支付时间
                    ];

                    $ord = [
                        'transaction_id' => $transaction_id,
                        'status' => 2,
                        'pay_time' => time(),// 支付时间
                    ];
                    // 更新数据
                    $upda = Db::name('order')->where('order_id', $order_number)->update($order_data);

                    if ($order['pid']) {
                        $goods = Db::name('order')->where('pid', $order['id'])->field('order_id,user_id,name,title,goods_id,num')->select();
                        foreach ($goods as $val) {
                            $item = Db::name('goods')->where('id', $val['goods_id'])->value('item');
                            $item = json_decode($item, true);
                            foreach ($item as &$val1) {
                                if ($val1['title'] == $val['title']) {
                                    $val1['stock'] = $val1['stock'] - $val['num'];
                                }
                            }
                            Db::name('user_cart')->where(['user_id' => $val['user_id'], 'name' => $val['name'], 'item' => $val['name'], 'goods_id' => $val['goods_id']])->delete();
                            Db::name('goods')->where('id', $val['goods_id'])->update(['item' => json_encode($item)]);
                            // Db::name('order')->where('order_id',$val['order_id'])->update($order_data);
                            Db::name('order')->where(['order_id' => $val['order_id'], 'pid' => 1])->update($order_data);
                            Db::name('order')->where(['order_id' => $val['order_id']])->where('pid', '<>', 1)->update($ord);
                        }
                    }
                    $where = ['user_id' => $order['user_id'], 'goods_id' => $order['goods_id'], 'name' => $order['name'], 'item' => $order['title']];
                    // 删除优惠券id
                    if ($order['cou_id']) {
                        Db::name('user_coupons')->where('id', $order['cou_id'])->setDec('num', 1);
                        Db::name('user_coupons')->where('id', $order['cou_id'])->update(['status' => 2]);
                    }
                    Db::name('user_cart')->where($where)->delete();
                    // 给上级返利
//                    model('user')::item($order['user_id'],$order_number);
                    model('user')::log($order['user_id'], $order_number);
                    model('user')::userVip($order['user_id'], $order_number);
                    if (!$upda) return $fail("修改订单状态失败,请稍后通知！");
//                    Log::write('订单:'.$order_number.'支付'.$total_fee.'元成功');
                    return true;
                } elseif ($message['return_code'] == 'FAIL') {
                    // 用户支付失败
                    return $fail('通信失败，请稍后再通知我');
                }
            } else {
                return $fail("通信失败，请稍后通知！");
            }
        });
        return $response;

    }


    // 秒杀商品
    public function killOrder()
    {
        //连接
        // $redis = new \Redis();
        // $redis->connect('127.0.0.1', 6379);
        $config = config('wechat_pay');
        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            Log::write('验签成功');
            Log::write($message);
            //微信支付交易号
            $transaction_id = $message['transaction_id'];
            $order_number = $message['out_trade_no'];
            //现金收款
            $official_receipts = $message['cash_fee'];
            //订单金额
            $total_fee = $message['total_fee'] / 100;
            //支付时间
            $pay_time = strtotime($message['time_end']);

            $order = Db::name('order')->field('id,user_id,order_id,goods_id,cou_id,title,num')->where(['order_id' => $order_number])->find();
            if (!$order) {
                return true;
            }
            // key
            // $key = 'list_seckill_goods_id_'.$order['goods_id'];
            if ($message['return_code'] == 'SUCCESS') {
//                Log::write("订单信息成功数据");
//                Log::write($message);
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    //支付成功
                    $order_data = [
//                        'order_time'=>$pay_time,
                        'transaction_id' => $transaction_id,
//                        'actual_price'=>$official_receipts,
                        'money' => $total_fee,
                        'status' => 2,
                        'pay_time' => time(),// 支付时间
                    ];
                    // 从链表的头部删除一个元素，返回删除的元素,因为pop操作是原子性，即使很多用户同时到达，也是依次执行
                    // $count = $redis->lpop($key);
                    // if (!$count) {
                    //     return ['msg'=>'已抢光！','data'=>'','code'=>0];
                    // }
                    //已抢购用户id队列
                    // $userListKey = 'user_goods_id_'.$data['goods_id'];
                    //判断该用户是否已经抢购过 该用户id是否在抢购用户集合中
                    // $userBuyStatus = $redis->sismember($userListKey,$data['user_id']);
                    // if($userBuyStatus){
                    //     return ['msg'=>'您已抢过！','data'=>'','code'=>0];
                    // }

                    // 将用户id添加到抢购成功用户集合中
                    // $redis->sadd($userListKey,$data['user_id']);
                    // $msg = '抢到的人为：'.$user['nickname'];
                    // 更新数据
                    $upda = Db::name('order')->where('order_id', $order_number)->update($order_data);
                    // 更改规格的库存
                    $item = Db::name('goods')->where('id', $order['goods_id'])->value('item');

                    $item = json_decode($item, true);
                    foreach ($item as &$val) {
                        if ($val['title'] == $order['title']) {
                            $val['stock'] = $val['stock'] - $order['num'];
                        }
                    }
                    // 删除优惠券id
                    if ($order['cou_id']) {
                        Db::name('user_coupons')->where('id', $order['cou_id'])->setDec('num', 1);
                        Db::name('user_coupons')->where('id', $order['cou_id'])->update(['status' => 2]);
                    }
                    $item = json_encode($item);
                    Db::name('goods')->where('id', $order['goods_id'])->update(['item' => $item]);
                    // 给上级返利
//                    model('user')::item($order['user_id'],$order_number);
                    model('user')::log($order['user_id'], $order_number);
                    model('user')::userVip($order['user_id'], $order_number);
                    if (!$upda) return $fail("修改订单状态失败,请稍后通知！");
//                    Log::write('订单:'.$order_number.'支付'.$total_fee.'元成功');
                    return true;
                } elseif ($message['return_code'] == 'FAIL') {
                    // 用户支付失败
                    return $fail('通信失败，请稍后再通知我');
                }
            } else {
                return $fail("通信失败，请稍后通知！");
            }
        });
        return $response;

    }


    /*
     * 更新
     * */
    public function upOrders()
    {
        $config = config('wechat_pay');
        $app = Factory::payment($config);
        $response = $app->handlePaidNotify(function ($message, $fail) {
            Log::write('验签成功');
            Log::write($message);
            //微信支付交易号
            $transaction_id = $message['transaction_id'];
            $order_number = $message['out_trade_no'];
            //现金收款
            $official_receipts = $message['cash_fee'];
            //订单金额
            $total_fee = $message['total_fee'] / 100;
            //支付时间
            $pay_time = strtotime($message['time_end']);

            $order = Db::name('order')->field('id,user_id,order_id,goods_id,title,num')->where(['order_id' => $order_number])->find();
            if (!$order) {
                return true;
            }
            if ($message['return_code'] == 'SUCCESS') {
//                Log::write("订单信息成功数据");
//                Log::write($message);
                // 用户是否支付成功
                if ($message['result_code'] === 'SUCCESS') {
                    //支付成功
                    $order_data = [
//                        'order_time'=>$pay_time,
                        'transaction_id' => $transaction_id,
//                        'actual_price'=>$official_receipts,
                        'money' => $total_fee,
                        'status' => 2,
                        'pay_time' => time(),// 支付时间
                    ];
                    // 更新数据
                    $upda = Db::name('order')->where('order_id', $order_number)->update($order_data);
                    // 更改规格的库存
                    $item = Db::name('goods')->where('id', $order['goods_id'])->value('item');

                    $item = json_decode($item, true);
                    foreach ($item as &$val) {
                        if ($val['title'] == $order['title']) {
                            $val['stock'] = $val['stock'] - $order['num'];
                        }
                    }

                    $item = json_encode($item);
                    Db::name('goods')->where('id', $order['goods_id'])->update(['item' => $item]);
                    // 给上级返利
//                    model('user')::item($order['user_id'],$order_number);
                    model('user')::userVip($order['user_id'], $order_number);
                    if (!$upda) return $fail("修改订单状态失败,请稍后通知！");
//                    Log::write('订单:'.$order_number.'支付'.$total_fee.'元成功');
                    return true;
                } elseif ($message['return_code'] == 'FAIL') {
                    // 用户支付失败
                    return $fail('通信失败，请稍后再通知我');
                }
            } else {
                return $fail("通信失败，请稍后通知！");
            }
        });
        return $response;
    }




    // -------------推送信息------------------

    /*
    * 微信小程序消息订阅
   */
    public function actionSubmessage($order_id)
    {
        // 查询订单信息
        $order = Db::name('order')->where('order_id', $order_id)->field('order_id,user_id,pay_time,money,name,title')->find();

        // 查询用户信息
        $user = Db::name('user')->where('id', $order['user_id'])->field('nickname,openid')->find();
        $config = config('mini_program');
        //配置appid
        $appid = $config['app_id'];
        //配置appscret
        $secret = $config['secret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;

        //获取access_token
        $access_token = $this->geturl($url)["access_token"];
        $urlz = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $access_token;
        //模板id
        $template_id = "dQLcxSyZm5l1X3lJMwbqQeAQUJSTvXIE7vMZ2LhhtDM";
        $data = [];
        //接收者（用户）的 openid
        $data['touser'] = $user['openid'];
        //所需下发的订阅模板id
        $data['template_id'] = $template_id;
        //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
        $data['page'] = "pages/index/index";

        //模板内容 phrase date thing 这些类型有字符长短要求，注意看文档
        $data['data'] = [
            "phrase2" => ['value' => $order_id],
            "phrase6" => ['value' => $order['pay_time']],
            "date14" => ['value' => $order['money']],
            "date8" => ['value' => $order['name'] . $order['title']],
            'thing18' => ['value' => '您已下单成功']
        ];
        //跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
        // $data['miniprogram_state'] = 'developer';
        $data['miniprogram_state'] = 'trial';
        $dat = $this->posturl($urlz, $data);

        return ['msg' => '添加成功', 'data' => $dat, 'code' => 1];

    }


    /*
    * curl get请求封装,返回json数据格式数据
    */
    public function geturl($url)
    {
        $headerArray = array("Content-type:application/json;", "Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output, true);
        return $output;
    }


    /*
     * curl post请求封装,返回json数据格式数据
    */
    public function posturl($url, $data)
    {
        $data = json_encode($data);
        $headerArray = array("Content-type:application/json;charset='utf-8'", "Accept:application/json");
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headerArray);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return json_decode($output, true);
    }


}